package com.zl.data.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.zl.data.config.DataConstant;

/**
 * @author ZL @朱林</a>
 * @Version 1.0
 * @Description TODO
 * @date 2021/01/08  14:38
 */
public class DataOpenHelper extends SQLiteOpenHelper {
    private static final String SQL_CREATE_ENTRIES =
        String.format("CREATE TABLE %s ( %s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT NOT NULL UNIQUE, %s BLOB)", DataBeanInfo.TABLE_NAME, DataBeanInfo.ID, DataBeanInfo.KEY, DataBeanInfo.VALUE);

    private static final String SQL_INDEX_ENTRIES = String.format("CREATE INDEX if not exists index_name on %s( %s)", DataBeanInfo.TABLE_NAME, DataBeanInfo.KEY);

    private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + DataBeanInfo.TABLE_NAME;

    public DataOpenHelper(@Nullable Context context) {
        super(context, DataConstant.getDatabaseName(), null, DataConstant.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
        db.execSQL(SQL_INDEX_ENTRIES);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}
